package com.kingtone.rongji;

import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.Header;
import org.apache.http.HttpStatus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.kingtone.rongji.adapter.OrdeDetailProudctAdapter;
import com.kingtone.rongji.adapter.PromotionAdapter;
import com.kingtone.rongji.biz.Address;
import com.kingtone.rongji.biz.OrderProduct;
import com.kingtone.rongji.biz.Product;
import com.kingtone.rongji.biz.PromotionCode;
import com.kingtone.rongji.tool.AppContasts;
import com.kingtone.rongji.tool.CartUtils;
import com.kingtone.rongji.tool.RongJiRestClient;
import com.kingtone.rongji.tool.RongJiUtils;
import com.kingtone.rongji.tool.SharedPreferencesUtil;
import com.kingtone.rongji.ui.MyRadioGroup;
import com.kingtone.rongji.ui.ToastManager;
import com.kingtone.rongji.ui.MyRadioGroup.OnCheckedChangeListener;
import com.kingtone.rongji.ui.NoScrollListview;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.BaseJsonHttpResponseHandler;

public class OrderSummitActivity extends BaseActivity
{

	// private static final String TAG = "OrderSummitActivity";

	private Activity mContext;
	private NoScrollListview productListView = null;
	private RelativeLayout selectStoreAddress = null; // 自提点layout
	private Button summitBtn = null;
	private ArrayList<Product> prodList = null;
	private ArrayList<OrderProduct> newProductList = null;
	private TextView storeNameTextView = null; // 自提点名称
	private TextView storeAddressTextView = null;// 自提点地址

	private TextView receiveName = null;// 收货人姓名
	private TextView receivePhone = null;//收货人手机号
	private TextView receiverRegion = null;// 收货人地区
	private TextView receiverAdd = null;// 收货人地址
	private Address defaultAdd = null;

	private RelativeLayout changeShippingAdd = null;
	private MyRadioGroup radioGroup = null;
	/*
	 * private RadioButton radioOnline = null; //在线支付 private RadioButton
	 * radioSelf = null; //上门自提 private RadioButton radioCod = null; //货到付款
	 */
	private int arrivePay; // 0-非货到付款 1-货到付款订单
	private int shippingModeId = 100; // 100 = 物流配送，101 = 上门自提， 102 = 货到付款

	private TextView selfTitle = null;// 自提点标题
	private CheckBox radioOutofXian = null;
	private CheckBox radioInofXian = null;
	private double totalAmount = 0.0; // 订单合计金额
	private double discountAmount = 0.0;// 订单总折扣
	private double payAmount = 0.0; // 订单应付金额
	private double shippingCharge = 0.0; // 订单运费

	private TextView summitAmountTextView = null; // 应付金额
	private TextView payAmountTextView = null; // 总计
	private TextView disCountTextView = null; // 折扣
	private TextView subtotalTextView = null; // 小计
	private TextView shippingChargeTextView = null; // 运费
	private int shippingId;
	private TextView userMemo = null;
	private Spinner promotionSpinner = null;
	private PromotionAdapter promotionAdapter = null;
	private TextView noPromotion = null;
	private ArrayList<Address> list = null;
	private String customerUserName = "";
	private ArrayList<PromotionCode> promotionList = null;
	private String userCardCode = null;
	private boolean isCanGiftOrder = true;//订单能否送礼
	private String notGiftName = null;
	
	private View lineLayout;
	private RelativeLayout onlineLayout;
	private RelativeLayout myselfLayout;
	private RelativeLayout codLayout;
	private RadioButton radioOnline = null;
	private RadioButton radioMyself = null;
	private RadioButton radioCod = null;
	
	//订单类型
	private int orderType = 0;
	
	@SuppressWarnings("unchecked")
	@Override
	protected void onCreate(Bundle paramBundle)
	{
		super.onCreate(paramBundle);
		this.mContext = this;
		this.setContentView(R.layout.activity_order_summit);
		Intent intent = getIntent();
		if (intent.hasExtra(AppContasts.CART_PRODUCT_LIST))
		{
			prodList = (ArrayList<Product>) intent.getSerializableExtra(AppContasts.CART_PRODUCT_LIST);
			if (prodList != null)
			{
				newProductList = new ArrayList<OrderProduct>();

				for (Product prod : prodList)
				{
					OrderProduct newProduct = new OrderProduct();
					newProduct.setProductId(prod.getProductId());//"10050002004"
					newProduct.setProductName(prod.getProductName());
					newProduct.setQuantity(prod.getQuantity());/*10*/
					newProduct.setWeight(prod.getWeight());
					newProduct.setUnitPrice(prod.getUnitPrice());
					newProduct.setPromotionType(prod.getPromotionType());
					newProductList.add(newProduct);
					if(prod.getGiftShippingType() != 1)
					{
						isCanGiftOrder = false;
						notGiftName = prod.getProductName();
					}
				}
			}
		}
		setDefaultAdd(getIntent());
		setupView();
		getStoreList();
		
		
	}

	private void setupView()
	{
		productListView = (NoScrollListview) findViewById(R.id.summit_order_products_list);
		if (prodList != null)
		{
			OrdeDetailProudctAdapter adapter = new OrdeDetailProudctAdapter(mContext, prodList);
			productListView.setAdapter(adapter);

		}
		// 选择自提地点
		selectStoreAddress = (RelativeLayout) findViewById(R.id.submit_select_store_address);
		selectStoreAddress.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(OrderSummitActivity.this, StoreListActivity.class);
				if(list != null && list.size() > 0)
				{
					intent.putExtra("storeList", list);
				}
				if(defaultAdd != null)
				{
					intent.putExtra("defaultAdd", defaultAdd);
				}
				startActivityForResult(intent, 100);
			}
		});
		lineLayout = (View) findViewById(R.id.line_layout);
		onlineLayout = (RelativeLayout) findViewById(R.id.online_pay_layout);
		
		myselfLayout = (RelativeLayout) findViewById(R.id.myself_pay_layout);
		codLayout = (RelativeLayout) findViewById(R.id.cod_layout);
		userMemo = (TextView) findViewById(R.id.summit_order_comments);
		storeNameTextView = (TextView) findViewById(R.id.order_submit_store_store_name);
		storeAddressTextView = (TextView) findViewById(R.id.order_submit_store_store_address);

		summitBtn = (Button) findViewById(R.id.summit_order);
		summitBtn.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				if (newProductList != null && newProductList.size() > 0)
				{
					if (defaultAdd != null)
					{
						shippingId = defaultAdd.getShippingId();
					}
					String comments = userMemo.getText().toString();
					createOrder(arrivePay, newProductList, shippingId, comments);
				}
				else
				{
					ToastManager.show(mContext, "不能连续提交两次订单！");
				}
			}
		});

		changeShippingAdd = (RelativeLayout) findViewById(R.id.submit_change_shipping_address);
		changeShippingAdd.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				Intent addressIntent = new Intent(OrderSummitActivity.this, ReceiveAddressActivity.class);
				startActivityForResult(addressIntent, 201);
			}
		});
		
		selfTitle = (TextView) findViewById(R.id.submit_selef_title);
		radioOnline = (RadioButton) findViewById(R.id.radio_online_pay);
		radioMyself = (RadioButton) findViewById(R.id.radio_receive_by_selft);
		radioCod = (RadioButton) findViewById(R.id.radio_cod);
		
		radioInofXian= (CheckBox) findViewById(R.id.radio_gift_xian_in);
		radioInofXian.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
		{

			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
			{
				if(selectStoreAddress!= null && selfTitle != null)
				{
					selectStoreAddress.setVisibility(View.GONE);
					selfTitle.setVisibility(View.GONE);
					radioOnline.setChecked(true);
					radioMyself.setChecked(false);
					radioCod.setChecked(false);
					arrivePay = 0;
					selfTitle.setVisibility(View.GONE);
					selectStoreAddress.setVisibility(View.GONE);
					shippingModeId = 100;	
					// 更新订单费用
					setOrderCost(-1, 6);
				}
				if(!isCanGiftOrder)
				{
					notGiftToast();
					radioInofXian.setChecked(false);
					return;
				}
				
				if(isChecked)
				{
					radioOutofXian.setChecked(false);
					lineLayout.setVisibility(View.GONE);
					myselfLayout.setVisibility(View.GONE);
					codLayout.setVisibility(View.GONE);
					
				}else
				{
					lineLayout.setVisibility(View.VISIBLE);
					myselfLayout.setVisibility(View.VISIBLE);
					codLayout.setVisibility(View.VISIBLE);
				}
			}
			
		});
		radioOutofXian= (CheckBox) findViewById(R.id.radio_gift_xian_out);
		radioOutofXian.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
		{

			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
			{
				if(selectStoreAddress!= null && selfTitle != null)
				{
					selectStoreAddress.setVisibility(View.GONE);
					selfTitle.setVisibility(View.GONE);
					radioOnline.setChecked(true);
					radioMyself.setChecked(false);
					radioCod.setChecked(false);
					arrivePay = 0;
					selfTitle.setVisibility(View.GONE);
					selectStoreAddress.setVisibility(View.GONE);
					shippingModeId = 100;	
					// 更新订单费用
					setOrderCost(-2, 6);
				}
				if(!isCanGiftOrder)
				{
					notGiftToast();
					radioOutofXian.setChecked(false);
					return;
				}
				if(isChecked)
				{
					radioInofXian.setChecked(false);
					lineLayout.setVisibility(View.GONE);
					myselfLayout.setVisibility(View.GONE);
					codLayout.setVisibility(View.GONE);
					
				}else
				{
					lineLayout.setVisibility(View.VISIBLE); 
					myselfLayout.setVisibility(View.VISIBLE);
					codLayout.setVisibility(View.VISIBLE);
				}
			}
		});
		
		//设置订单类型
		if(radioInofXian.isChecked() || radioOutofXian.isChecked())
		{
			orderType = 6;
		}else
		{
			orderType = 0;
		}
		if(radioInofXian.isChecked())
		{
			shippingId = -1;
		}
		if(radioOutofXian.isChecked())
		{
			shippingId = -2;
		}
		    
	     onlineLayout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				radioOnline.setChecked(true);
				radioMyself.setChecked(false);
				radioCod.setChecked(false);
				arrivePay = 0;
				selfTitle.setVisibility(View.GONE);
				selectStoreAddress.setVisibility(View.GONE);
				shippingModeId = 100;	
				// 更新订单费用
				setOrderCost(shippingId, orderType);
			}
		});
	 
	   myselfLayout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(!TextUtils.isEmpty(storeNameTextView.getText()) && !TextUtils.isEmpty(storeAddressTextView.getText()))
            	{
            		selfTitle.setVisibility(View.VISIBLE);
    				selectStoreAddress.setVisibility(View.VISIBLE);
            	}else
            	{
            		selfTitle.setVisibility(View.GONE);
    				selectStoreAddress.setVisibility(View.GONE);
    				Toast.makeText(mContext, "暂无自提点", Toast.LENGTH_SHORT).show();
    				return;
            	}
				radioOnline.setChecked(false);
				radioMyself.setChecked(true);
				radioCod.setChecked(false);
				arrivePay = 0;
            	
				shippingModeId = 101;
				// 更新订单费用
				if(defaultAdd!= null)
				{
					setOrderCost(defaultAdd.getShippingId(), orderType);
				}
			}
		});
	   
	   codLayout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				radioOnline.setChecked(false);
				radioMyself.setChecked(false);
				radioCod.setChecked(true);
				arrivePay = 1;
				selfTitle.setVisibility(View.GONE);
				selectStoreAddress.setVisibility(View.GONE);
				shippingModeId = 102;
				// 更新订单费用
				if(defaultAdd!= null)
				{
					setOrderCost(defaultAdd.getShippingId(), orderType);
				}
				
			}
		});
	   
	   radioGroup = (MyRadioGroup) findViewById(R.id.radioGroup);
	   radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener()
		{
			@Override
			public void onCheckedChanged(MyRadioGroup group, int checkedId)
			{
				if (checkedId == R.id.radio_cod)
				{
					arrivePay = 1;
				} else
				{
					arrivePay = 0;
				}
				// 100 = 物流配送，101 = 上门自提， 102 = 货到付款
				if (checkedId == R.id.radio_online_pay)
				{
					selfTitle.setVisibility(View.GONE);
					selectStoreAddress.setVisibility(View.GONE);
					shippingModeId = 100;

				} else if (checkedId == R.id.radio_receive_by_selft)
				{
					selfTitle.setVisibility(View.VISIBLE);
					selectStoreAddress.setVisibility(View.VISIBLE);
					shippingModeId = 101;

				} else
				{
					selfTitle.setVisibility(View.GONE);
					selectStoreAddress.setVisibility(View.GONE);
					shippingModeId = 102;
				}

				// 更新订单费用
				if(defaultAdd!= null)
				{
					setOrderCost(defaultAdd.getShippingId(), orderType);
				}
			}
		});
		promotionSpinner = (Spinner) findViewById(R.id.spinner_promotion_code);
		promotionSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
		{

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
			{
				PromotionCode promotionCode = promotionList.get(position);
				if(promotionCode != null)
				{
					userCardCode = promotionCode.getUserCardCode();
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent)
			{
				
			}
			
		});
		noPromotion = (TextView) findViewById(R.id.order_submit_no_youhui_note);
		subtotalTextView = (TextView) findViewById(R.id.order_sub_total);// 小计
		disCountTextView = (TextView) findViewById(R.id.order_discount);// 折扣
		shippingChargeTextView = (TextView) findViewById(R.id.order_shipping_charge);// 运费
		payAmountTextView = (TextView) findViewById(R.id.order_pay_amount);// 应付金额
		summitAmountTextView = (TextView) findViewById(R.id.summit_amount);// 应付金额
		summitAmountTextView.setText(getString(R.string.order_detail_total_price) + "0.00");
		// 更新订单费用
		if(defaultAdd!= null)
		{
			setOrderCost(defaultAdd.getShippingId(), orderType);
		}
		// 获取订单可用的优惠卷
		getPromotionCode();
	}

	private void notGiftToast()
	{
		Toast.makeText(mContext, notGiftName + getString(R.string.can_not_gift), Toast.LENGTH_SHORT).show();
	}
	/**
	 * 更新订单费用
	 */
	private void setOrderCost(int shippingId, int orderType)
	{
		// 计算费用
		if (defaultAdd != null && newProductList != null && newProductList.size() > 0)
		{
			calculateOrder(arrivePay, shippingId,orderType, newProductList);
		}
	}

	/**
	 * 设置默认地址
	 */
	private void setDefaultAdd(Intent data)
	{
		if(null == data) {
			return;
		}
		
		if (data.hasExtra("defaultAddress"))
		{
			defaultAdd = (Address) data.getSerializableExtra("defaultAddress");
		}
		
		if (defaultAdd != null)
		{
			customerUserName = defaultAdd.getShipTo();
		}

		receiveName = (TextView) findViewById(R.id.summit_receiver_name);
		receivePhone = (TextView) findViewById(R.id.summit_receiver_phone);
		
		receiverRegion = (TextView) findViewById(R.id.summit_receiver_region);
		receiverAdd = (TextView) findViewById(R.id.summit_receiver_address_address);

		if (defaultAdd != null)
		{

			receiveName.setText(getString(R.string.order_detail_reciver) + defaultAdd.getShipTo());
			receivePhone.setText(defaultAdd.getCellPhone());
			receiverRegion.setText(defaultAdd.getRegionAddress());
			receiverAdd.setText(defaultAdd.getAddress());
			
			setOrderCost(defaultAdd.getShippingId(), orderType);
		}
	}

	/**
	 * 创建订单
	 * 
	 * @param arrivePay
	 * @param giftList
	 * @param isInvoice
	 * @param invoiceTitle
	 * @param orderExpensePoint
	 * @param orderGiftCardAmount
	 * @param orderNumber
	 * @param orderType
	 * @param productList
	 * @param receiveType
	 * @param shippingId
	 * @param shippingModeId
	 * @param userMemo
	 */
	@SuppressWarnings("rawtypes")
	private void createOrder(int arrivePay, ArrayList<OrderProduct> productList, int shippingId, String userMemo)
	{
		HashMap<String, Object> params = new HashMap<String, Object>();
		Gson gson = new Gson();
		params.put("ArrivePay", arrivePay);
		SharedPreferencesUtil instance = SharedPreferencesUtil.getInstance(mContext);
		String userId = instance.getString(AppContasts.USERID_KEY);
		// String userName = instance.getString(AppContasts.USERNAME_KEY);
		params.put("InUser", userId);
		params.put("CurrentUserId", userId);
		params.put("CustomerUserId", userId);
		params.put("OrderSource", 4);//区分下单设备来源
		params.put("CustomerUserName", customerUserName);

		params.put("OrderType", orderType); // 订单类型
		if (productList != null && productList.size() > 0)
		{
			params.put("ProductList", productList); // 产品列表

		}
		params.put("ShippingId", shippingId); // 用户收货地址编号
		params.put("ShippingModeId", shippingModeId);// 物流配送方式编号
		String storeStr = "";
		if(selectStoreAddress.getVisibility() == View.VISIBLE)
		{
			String storeName = storeNameTextView.getText().toString();
			String storeAdd = storeAddressTextView.getText().toString();
			storeStr = getString(R.string.order_submit_ziti) + storeName + storeAdd; 
		}
		if(TextUtils.isEmpty(userMemo))
		{
			userMemo = storeStr;
		}else
		{
			userMemo = userMemo + " " + storeStr;
		}
		params.put("UserMemo", userMemo);// 用户订单备注和自提点名称、地址
		if(!TextUtils.isEmpty(userCardCode))
		{
			params.put("PromotionCode", userCardCode);// 用户订单备注
		}
		RongJiRestClient.createOrder(mContext, gson.toJson(params), new BaseJsonHttpResponseHandler()
		{

			@Override
			public void onStart()
			{
				RongJiUtils.showEmptyProgress(mContext);
			}

			@Override
			public void onFailure(int arg0, Header[] arg1, Throwable arg2, String arg3, Object arg4)
			{

				RongJiUtils.dismissProgress();

			}

			@Override
			public void onSuccess(int statusCode, Header[] arg1, String response, Object arg3)
			{
				RongJiUtils.dismissProgress();
				if (statusCode == HttpStatus.SC_OK)
				{
					if (response != null && !new String(response).equalsIgnoreCase("null"))
					{
						String result = new String(response);
						JSONTokener jsonParser = new JSONTokener(result);
						try
						{
							JSONObject resultObj = (JSONObject) jsonParser.nextValue();
							boolean errorCode = resultObj.optBoolean("Status");
							if (errorCode)
							{
								//下单成功 清空购物车
								newProductList = null;
								CartUtils.deleteProductList(mContext, prodList);
								
								//获取订单号
								String orderNo = resultObj.optString("Tag");
								if (shippingModeId == 102) // 货到付款
								{
									Intent intent = new Intent(OrderSummitActivity.this, OrderSummitSuccessActivity.class);
									intent.putExtra("payAmount", payAmount);
									intent.putExtra("orderNo", orderNo);
									startActivity(intent);
								} else
								{
									//跳转到提示付款页面
									Intent intent = new Intent(OrderSummitActivity.this, PayNoticeActivity.class);
									intent.putExtra("orderNo", orderNo);
									String subject = mContext.getString(R.string.welcome_img) +"_"+ orderNo;
									intent.putExtra("subject", subject);
									if(TextUtils.isEmpty(customerUserName))
									{
										customerUserName = SharedPreferencesUtil.getInstance(mContext).getString(AppContasts.USERNAME_KEY);
										
									}
									if(!TextUtils.isEmpty(customerUserName))
									{
										customerUserName  = customerUserName + "_";
									}
									intent.putExtra("body", customerUserName  + orderNo);
									intent.putExtra("payAmount", payAmount);
									intent.putExtra("orderType", orderType);
									startActivity(intent);
								}

							} else
							{
								String errorMsg = resultObj.optString("ErrorMessage");
								if (!TextUtils.isEmpty(errorMsg))
								{
									Toast.makeText(mContext, errorMsg, Toast.LENGTH_SHORT).show();
								}
							}

						} catch (JSONException e)
						{
							e.printStackTrace();
						}
					}
				}
			}

			@Override
			protected Object parseResponse(String response, boolean arg1) throws Throwable
			{
				return null;
			}
		});
	}

	/**
	 * 计算费用
	 * 
	 * @param arrivePay
	 * @param shippingId
	 * @param shippingModeId
	 * @param productList
	 */
	@SuppressWarnings("rawtypes")
	private void calculateOrder(int arrivePay, int shippingId, int orderType, ArrayList<OrderProduct> productList)
	{
		HashMap<String, Object> params = new HashMap<String, Object>();
		Gson gson = new Gson();
		params.put("ArrivePay", arrivePay);
		SharedPreferencesUtil instance = SharedPreferencesUtil.getInstance(mContext);
		String userId = instance.getString(AppContasts.USERID_KEY);
		params.put("CustomerUserId", userId);
		params.put("OrderType", orderType);
		params.put("ShippingId", shippingId); // 用户收货地址编号
		params.put("ShippingModeId", shippingModeId);// 物流配送方式编号
		// params.put("OrderType", 0);
		if (productList != null && productList.size() > 0)
		{
			params.put("ProductList", productList); // 产品列表
		}

		RongJiRestClient.calculateOrder(mContext, gson.toJson(params), new BaseJsonHttpResponseHandler()
		{

			@Override
			public void onStart()
			{
				RongJiUtils.showEmptyProgress(mContext);
			}

			@Override
			public void onFailure(int arg0, Header[] arg1, Throwable arg2, String arg3, Object arg4)
			{
				RongJiUtils.dismissProgress();

			}

			@Override
			public void onSuccess(int statusCode, Header[] arg1, String responseString, Object arg3)
			{
				RongJiUtils.dismissProgress();

				if (statusCode == HttpStatus.SC_OK)
				{
					if (responseString != null && !new String(responseString).equalsIgnoreCase("null"))
					{
						String result = new String(responseString);
						JSONTokener jsonParser = new JSONTokener(result);
						try
						{
							JSONObject calculate = (JSONObject) jsonParser.nextValue();
							if (calculate.has("TotalAmount"))
							{
								totalAmount = calculate.getDouble("TotalAmount");
							}

							if (calculate.has("DiscountAmount"))
							{
								discountAmount = calculate.getDouble("DiscountAmount");
							}
							if (calculate.has("PayAmount"))
							{
								payAmount = calculate.getDouble("PayAmount");
							}
							if (calculate.has("ShippingCharge"))
							{
								shippingCharge = calculate.getDouble("ShippingCharge");
							}

							subtotalTextView.setText("" + totalAmount);
							disCountTextView.setText("-" + discountAmount);
							shippingChargeTextView.setText("" + shippingCharge);
							payAmountTextView.setText("" + payAmount);
							summitAmountTextView.setText(getString(R.string.order_detail_total_price) + payAmount);

						} catch (JSONException e)
						{
							e.printStackTrace();
						}
					}
				}
			}

			@Override
			protected Object parseResponse(String arg0, boolean arg1) throws Throwable
			{
				return null;
			}
		});
	}

	@SuppressWarnings("rawtypes")
	private void getPromotionCode()
	{
		HashMap<String, Object> params = new HashMap<String, Object>();
		Gson gson = new Gson();
		SharedPreferencesUtil instance = SharedPreferencesUtil.getInstance(mContext);
		String userId = instance.getString(AppContasts.USERID_KEY);
		params.put("CustomerUserId", userId);
		if (newProductList != null && newProductList.size() > 0)
		{
			params.put("ProductList", newProductList); // 产品列表

		}
		RongJiRestClient.getPromotionCode(mContext, gson.toJson(params), new BaseJsonHttpResponseHandler()
		{

			@Override
			public void onStart()
			{
				// RongJiUtils.showEmptyProgress(mContext);
			}

			@Override
			public void onFailure(int arg0, Header[] arg1, Throwable arg2, String arg3, Object arg4)
			{

				// RongJiUtils.dismissProgress();

			}

			@Override
			public void onSuccess(int statusCode, Header[] arg1, String response, Object arg3)
			{
				// RongJiUtils.dismissProgress();
				if (statusCode == HttpStatus.SC_OK)
				{
					if (response != null && !new String(response).equalsIgnoreCase("null"))
					{
						String result = new String(response);
						JSONTokener jsonParser = new JSONTokener(result);
						try
						{
							JSONObject resultObj = (JSONObject) jsonParser.nextValue();
							if (resultObj.has("PromotionCodeCustomerList"))
							{
								JSONArray pArray = resultObj.getJSONArray("PromotionCodeCustomerList");
								Gson gson = new Gson();
								JsonParser parser = new JsonParser();
								JsonElement element = parser.parse(pArray.toString());
								if (element instanceof JsonArray)
								{
									promotionList = new ArrayList<PromotionCode>();
									JsonArray array = element.getAsJsonArray();
									for (JsonElement myOrder : array)
									{
										PromotionCode object = gson.fromJson(myOrder, PromotionCode.class);
										promotionList.add(object);
									}
									promotionAdapter = new PromotionAdapter(mContext, promotionList);
									promotionSpinner.setAdapter(promotionAdapter);
								}
							}
							if (promotionList != null && promotionList.size() > 0)
							{
								noPromotion.setVisibility(View.GONE);
								promotionSpinner.setVisibility(View.VISIBLE);
							} else
							{
								noPromotion.setVisibility(View.VISIBLE);
								promotionSpinner.setVisibility(View.GONE);
							}
						} catch (JSONException e)
						{
							e.printStackTrace();
						}
					}
				}
			}

			@Override
			protected Object parseResponse(String response, boolean arg1) throws Throwable
			{
				return null;
			}
		});
	}

	public void onBackPressed()
	{
		if(null!=defaultAdd) {
			Intent intent = new Intent(OrderSummitActivity.this, CartActivity.class);
			intent.putExtra("defaultAddress", defaultAdd);
			setResult(RESULT_OK, intent);
		}
		finish();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		if (requestCode == 100)
		{
			if (resultCode == RESULT_OK)
			{
				if (data != null)
				{
					String storeName = null;
					String storeAdd = null;

					if (data.hasExtra(AppContasts.STORE_NAME))
					{
						storeName = data.getStringExtra(AppContasts.STORE_NAME);
					}
					if (data.hasExtra(AppContasts.STORE_NAME))
					{
						storeAdd = data.getStringExtra(AppContasts.STORE_ADDRESS);
					}

					storeNameTextView.setText(storeName);
					storeAddressTextView.setText(storeAdd);
				}
			}
		} else if (requestCode == 201)
		{
			if (resultCode == RESULT_OK)
			{
				setDefaultAdd(data);
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	
	/**
	 * 获取自提的列表
	 */
	private void getStoreList()
	{
		RongJiRestClient.getShippingAddress("100", "-1", new AsyncHttpResponseHandler() {

			@Override
			public void onStart() {
				RongJiUtils.showEmptyProgress(mContext);
			}
			
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
				RongJiUtils.dismissProgress();
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				RongJiUtils.dismissProgress();
				
				if(arg2 != null && !new String(arg2).equalsIgnoreCase("null"))
				{
					String result = new String(arg2);
					Gson gson = new Gson();
					JsonParser parser = new JsonParser();
					JsonArray array = parser.parse(result).getAsJsonArray();
					list = new ArrayList<Address>();
					int i = 0;
					for(JsonElement obj:array) {
						i++;
						Address object = gson.fromJson(obj, Address.class);
						list.add(object);
						if(i==1)
						{
							storeNameTextView.setText(object.getRegionAddress());
							storeAddressTextView.setText(object.getAddress());
						}
						String defaultShippingId =  SharedPreferencesUtil.getInstance(mContext).getString(AppContasts.DEFAULT_STORE_ADDRESS_SHIPPING_ID);
						if(!TextUtils.isEmpty(defaultShippingId) && object.getShippingId() == Integer.parseInt(defaultShippingId))
						{
							storeNameTextView.setText(object.getRegionAddress());
							storeAddressTextView.setText(object.getAddress());
							list.set(0, object);
							list.remove(i - 1);
						}	
					}
				}
			}	
		});
	}
}
